<?php
class Xtutuquan{
    /**
     * 友好显示var_dump
     */
    static public function dump( $var, $echo = true, $label = null, $strict = true ) {
        $label = ( $label === null ) ? '' : rtrim( $label ) . ' ';
        if ( ! $strict ) {
            if ( ini_get( 'html_errors' ) ) {
                $output = print_r( $var, true );
                $output = "<pre>" . $label . htmlspecialchars( $output, ENT_QUOTES ) . "</pre>";
            } else {
                $output = $label . print_r( $var, true );
            }
        } else {
            ob_start();
            var_dump( $var );
            $output = ob_get_clean();
            if ( ! extension_loaded( 'xdebug' ) ) {
                $output = preg_replace( "/\]\=\>\n(\s+)/m", "] => ", $output );
                $output = '<pre>' . $label . htmlspecialchars( $output, ENT_QUOTES ) . '</pre>';
            }
        }
        if ( $echo ) {
            echo $output;
            return null;
        } else
            return $output;
    }
    /**
     * 获取和设置配置参数 支持批量定义
     * @param string|array $name 配置变量
     * @param mixed $value 配置值
     * @param mixed $default 默认值
     * @return mixed
     */
    static public function C($name=null, $value=null,$default=null) {
        static $_config = array();
        // 无参数时获取所有
        if (empty($name)) {
            return $_config;
        }
        // 优先执行设置获取或赋值
        if (is_string($name)) {
            if (!strpos($name, '.')) {
                $name = strtoupper($name);
                if (is_null($value))
                    return isset($_config[$name]) ? $_config[$name] : $default;
                $_config[$name] = $value;
                return;
            }
            // 二维数组设置和获取支持
            $name = explode('.', $name);
            $name[0]   =  strtoupper($name[0]);
            if (is_null($value))
                return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
            $_config[$name[0]][$name[1]] = $value;
            return;
        }
        // 批量设置
        if (is_array($name)){
            $_config = array_merge($_config, array_change_key_case($name,CASE_UPPER));
            return;
        }
        return null; // 避免非法参数
    }
    static public function session($name='',$value='') {
    $prefix   =  'tutuquan';
    if(is_array($name)) { // session初始化 在session_start 之前调用
        if(isset($name['prefix'])) self::C('SESSION_PREFIX',$name['prefix']);
        if(self::C('VAR_SESSION_ID') && isset($_REQUEST[self::C('VAR_SESSION_ID')])){
            session_id($_REQUEST[self::C('VAR_SESSION_ID')]);
        }elseif(isset($name['id'])) {
            session_id($name['id']);
        }
        if('common' != APP_MODE){ // 其它模式可能不支持
            ini_set('session.auto_start', 0);
        }
        if(isset($name['name']))            session_name($name['name']);
        if(isset($name['path']))            session_save_path($name['path']);
        if(isset($name['domain']))          ini_set('session.cookie_domain', $name['domain']);
        if(isset($name['expire']))          ini_set('session.gc_maxlifetime', $name['expire']);
        if(isset($name['use_trans_sid']))   ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0);
        if(isset($name['use_cookies']))     ini_set('session.use_cookies', $name['use_cookies']?1:0);
        if(isset($name['cache_limiter']))   session_cache_limiter($name['cache_limiter']);
        if(isset($name['cache_expire']))    session_cache_expire($name['cache_expire']);
        if(isset($name['type']))            self::C('SESSION_TYPE',$name['type']);
        if(self::C('SESSION_TYPE')) { // 读取session驱动
            $type   =   self::C('SESSION_TYPE');
            $class  =   strpos($type,'\\')? $type : 'Think\\Session\\Driver\\'. ucwords(strtolower($type));
            $hander =   new $class();
            session_set_save_handler(
                array(&$hander,"open"),
                array(&$hander,"close"),
                array(&$hander,"read"),
                array(&$hander,"write"),
                array(&$hander,"destroy"),
                array(&$hander,"gc"));
        }
        // 启动session
        if(C('SESSION_AUTO_START'))  session_start();
    }elseif('' === $value){
        if(''===$name){
            // 获取全部的session
            return $prefix ? $_SESSION[$prefix] : $_SESSION;
        }elseif(0===strpos($name,'[')) { // session 操作
            if('[pause]'==$name){ // 暂停session
                session_write_close();
            }elseif('[start]'==$name){ // 启动session
                session_start();
            }elseif('[destroy]'==$name){ // 销毁session
                $_SESSION =  array();
                session_unset();
                session_destroy();
            }elseif('[regenerate]'==$name){ // 重新生成id
                session_regenerate_id();
            }
        }elseif(0===strpos($name,'?')){ // 检查session
            $name   =  substr($name,1);
            if(strpos($name,'.')){ // 支持数组
                list($name1,$name2) =   explode('.',$name);
                return $prefix?isset($_SESSION[$prefix][$name1][$name2]):isset($_SESSION[$name1][$name2]);
            }else{
                return $prefix?isset($_SESSION[$prefix][$name]):isset($_SESSION[$name]);
            }
        }elseif(is_null($name)){ // 清空session
            if($prefix) {
                unset($_SESSION[$prefix]);
            }else{
                $_SESSION = array();
            }
        }elseif($prefix){ // 获取session
            if(strpos($name,'.')){
                list($name1,$name2) =   explode('.',$name);
                return isset($_SESSION[$prefix][$name1][$name2])?$_SESSION[$prefix][$name1][$name2]:null;
            }else{

                return isset($_SESSION[$prefix][$name]) ? $_SESSION[$prefix][$name] : null;
            }
        }else{
            if(strpos($name,'.')){
                list($name1,$name2) =   explode('.',$name);
                return isset($_SESSION[$name1][$name2])?$_SESSION[$name1][$name2]:null;
            }else{
                return isset($_SESSION[$name]) ? $_SESSION[$name] : null;
            }
        }
    }elseif(is_null($value)){ // 删除session
        if($prefix){
            unset($_SESSION[$prefix][$name]);
        }else{
            unset($_SESSION[$name]);
        }
    }else{ // 设置session
        if($prefix){
            if (!isset($_SESSION[$prefix])) {
                $_SESSION[$prefix] = array();
            }
            $_SESSION[$prefix][$name]   =  $value;
        }else{
            $_SESSION[$name]  =  $value;
        }
    }
    }


    /**
     * @author Asa_yang <88683231@qq.com>
     * @link http://www.hoohg.com/
     * @copyright Copyright &copy; 2011-2013 Hoohg Software LLC
     * @param string $length 随机hash的长度
     * @return hash 返回生成的哈希字符串
     *
     */
    //随机hash生成
    static public function randStr($length=10){
        $hash='';
        $chars= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   //@#!~?:-
        $max=strlen($chars)-1;
//        mt_srand((double)microtime()*1000000);
        for($i=0;$i<$length;$i++){
            $hash .=$chars[mt_rand(0,$max)];
        }
        return $hash;
    }
    /**
     * 获取客户端IP地址
     */
    static public function getClientIP() {
        static $ip = NULL;
        if ( $ip !== NULL )
            return $ip;
        if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
            $arr = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );
            $pos = array_search( 'unknown', $arr );
            if ( false !== $pos )
                unset( $arr[$pos] );
            $ip = trim( $arr[0] );
        } elseif ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $ip = ( false !== ip2long( $ip ) ) ? $ip : '0.0.0.0';
        return $ip;
    }
    /**
     * 跳转页面 在基类中.
     * @author Asa_yang <88683231@qq.com>
     * @link http://www.hoohg.com/
     * @copyright Copyright &copy; 2011-2013 Hoohg Software LLC
     * @param string $message 弹窗提示文字 .
     * @param string $status 状态,为  success.
     * @param integer $time 跳转时间
     * @param string $url  跳转地址
     * @return html 返回弹窗界面
     */
    static public function redirect_message($message='操作成功',$status='success',$time=3,$url=false){

        $back_color ='#ff0000';
        if($status =='success'){
            $back_color= 'blue';
        }elseif($status == 'error'){
            $back_color= 'red';
        }
        if(is_array($url)){
            $route=isset($url[0]) ? $url[0] : '';
            $url=$this->createUrl($route,array_splice($url,1));
        }
        if ($url)
        {
            $url = "window.location.href='{$url}'";
        }
        else
        {
            $url = "history.back();";
        }
        $imagepath  = Yii::app()->baseUrl.'/static/admin/images/loading.gif';

        echo <<<HTML
			<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
			<html>
			<head>
			<title>页面提示</title>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
			<style type="text/css" rel="stylesheet">
			body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, textarea, p, blockquote, th, td, img, input, select {margin:0; padding:0;}
			dl, dt, dd, ul, ol, li{list-style:none; list-style-position:outside;}
			li, img {vertical-align:bottom;}
			.clear {font-size:0; line-height:0; height:0; clear:both; overflow:hidden;}
			.clearfix:after {clear: both;content: ".";display: block; height: 0;visibility: hidden;}
			* html .clearfix             { zoom: 1; } /* IE6 */
			*:first-child+html .clearfix { zoom: 1; } /* IE7 */
			/*全局*/
			body {background:#F4F4F4}
			.main {width:500px; position:absolute;left:50%; top:20%; margin:0 0 0 -250px; background:#FFFFFF; border:1px solid #DEDEDE; border-radius:5px; box-shadow:0 1px 3px #CCCCCC; padding:20px}
			h1 {font:normal 25px/50px "microsoft yahei"; color:#0085CC; margin:0 0 10px 0}
			#blue {color:#0085CC;}
			#red {color:-moz-activehyperlinktext};
			p {font:normal 14px/23px "microsoft yahei"; color:#797979}
			p a {margin:0 2px; color:#0055CC}
			</style>
			</head>
			<body >
				<div class="main">
				<h1 id="{$back_color}">{$message}</h1><br/><p>页面将在<span id="sec" style="color:{$back_color};">{$time}</span>秒内自动跳转，如果不想等待，请点击 <a href="javascript:history.back(-1);">这里</a>跳转。</p>
				<script type="text/javascript">
					var timer;
                    function run(){
                        var s = document.getElementById("sec");
                        if(s.innerHTML == 0){
                        	clearInterval(timer);
                        	{$url}
                            return false;
                        }
                        s.innerHTML = s.innerHTML * 1 - 1;

                    }
                    timer = window.setInterval("run();", 1000);
                </script>
			</div>
			</body>
			</html>
HTML;
        exit;

    }

    /*
     * cookie加密
     * 加密 不带第二个参数   解密第二个参数为1
     */

    static public function encryption($username,$type = 0){
        $key = md5(sha1(Yii::app()->params['cookieKey']));
        if(!$type){
            return base64_encode($username ^ $key);
        }
        $username = base64_decode($username);
        return $username ^ $key;
    }


    /**
     * 2014 2 17
     */
    /**
     * 设置cookie
     * 第三个参数必填   为time()+xxx秒
     */
    static public function _cookiesSet ($name = '', $value = '', $expire = 3600, $path = '', $domain = '', $secure = false)
    {

        $cookieSet = new CHttpCookie($name, $value);
        $expire && $cookieSet->expire = $expire;
        $path && $cookieSet->path = $path;
        $domain && $cookieSet->domain = $domain;
        $secure && $cookieSet->secure = $secure;
        Yii::app()->request->cookies[$name] = $cookieSet;
    }

    /**
     * 获取cookie
     */
    static public function _cookiesGet ($name, $once = false)
    {
        $cookie = Yii::app()->request->getCookies();
        if($cookie[$name]){
            $data = $cookie[$name]->value;
        }else{
            $data = '';
        }

        if ($once)
            unset($cookie[$name]);
        return $data;
    }

    /**
     * 清理cookie
     * @param  $name
     */
    static public  function _cookiesRemove ($name)
    {
        $cookie = Yii::app()->request->getCookies();
        unset($cookie[$name]);
    }

    static public function getEmailConfig(){
        //email 配置
        $value = Yii::app()->cache->get('system_email');
        if($value === false){
            // 因为在缓存中没找到，重新生成 $value
            $email_info = Config::model()->findAll('type=:type',array(':type'=>'email'));
            $data = array();
            foreach($email_info as $v){
                $data[$v->name] = $v->value;
            }
            Yii::app()->cache->set('system_email',$data);
            $value = $data;
        }
        return $value;
    }

    static public function _sendEmail($to,$Subject,$content){
        $value = self::getEmailConfig();
        $mailer = Yii::createComponent('ext.mailer.EMailer');
        $mailer->Host = $value['emailHost'];
        $mailer->IsSMTP();
        $mailer->SMTPAuth = true;
        $mailer->From = $value['emailFrom'];
        $mailer->AddReplyTo($value['emailFrom']);
        $mailer->AddAddress($to);
        $mailer->FromName = $value['emailFromName'];
        $mailer->Username = $value['emailFrom'];    //这里输入发件地址的用户名
        $mailer->Password = $value['emailPassword'];   //这里输入发件地址的密码
        $mailer->SMTPDebug = FALSE;   //设置SMTPDebug为true，就可以打开Debug功能，根据提示去修改配置
        $mailer->CharSet = 'UTF-8';
        $mailer->Subject = $Subject;
        $mailer->Body = $content;
        $status = $mailer->Send();
        return $status;
    }
    /**
     * 反引用一个引用字符串
     * @param  $string
     * @return string
     */
    static function stripslashes($string) {
        if(is_array($string)) {
            foreach($string as $key => $val) {
                $string[$key] = self::stripslashes($val);
            }
        } else {
            $string = stripslashes($string);
        }
        return $string;
    }
    /**
     * 返回经stripslashes处理过的字符串或数组
     * @param $string 需要处理的字符串或数组
     * @return mixed
     */
    static public function new_stripslashes($string) {
        if (!is_array($string)) return stripslashes($string);
        foreach($string as $key => $val) $string[$key] = self::new_stripslashes($val);
        return $string;
    }
    /**
     * 验证邮箱
     */
    public static function email( $str ) {
        if ( empty( $str ) )
            return true;
        $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
        if ( strpos( $str, '@' ) !== false && strpos( $str, '.' ) !== false ) {
            if ( preg_match( $chars, $str ) ) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    /**
     * 循环创建目录
     */
    static public function mkdir( $dir, $mode = 0777 ) {
        if ( is_dir( $dir ) || @mkdir( $dir, $mode))
            return true;
        if ( !self::mkdir(dirname($dir), $mode))
            return false;
        return @mkdir( $dir, $mode );
    }
    /**
     * 将字符串转换为数组
     *
     * @param	string	$data	字符串
     * @return	array	返回数组格式，如果，data为空，则返回空数组
     */
    static function string2array($data) {
        if($data == '') return array();
        @eval("\$array = $data;");
        return @$array;
    }
    /**
     * 将数组转换为字符串
     *
     * @param	array	$data		数组
     * @param	bool	$isformdata	如果为0，则不使用new_stripslashes处理，可选参数，默认为1
     * @return	string	返回字符串，如果，data为空，则返回空
     */
    static function array2string($data, $isformdata = 1) {
        if($data == '') return '';
        if($isformdata) $data = self::new_stripslashes($data);
        return addslashes(var_export($data, TRUE));
    }


    /*
      *功能：下载远程图片保存到本地
      *参数：远程图片url,
      *     文件夹路径，
      *     文件路径
      *当保存文件名称为空时则使用远程文件原来的名称
      */
    static public function getImage($url,$savefile,$filename){
        if($url==''){return false;}
        if(!is_dir($savefile)) mkdir($savefile, 0777,true);
        if(!is_readable($savefile)) chmod($savefile, 0777);
        $hander = curl_init();
        $fp = fopen($filename,'wb');
        curl_setopt($hander,CURLOPT_URL,$url);
        curl_setopt($hander,CURLOPT_FILE,$fp);
        curl_setopt($hander,CURLOPT_HEADER,0);
        curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($hander,CURLOPT_TIMEOUT,60);
        $output = curl_exec($hander);
        curl_close($hander);
        fclose($fp);
        require_once('Tp/ThinkImage/Image.class.php');
        $image = new Image();
        $thumbPath = $savefile.'/200x200.jpg';
        $unfoldPath = $savefile.'/36x36.jpg';
        $image->open($filename);
        $image->thumb(200, 200)->save($thumbPath);
        $image->open($filename);
        $image->thumb(36, 36)->save($unfoldPath);
        return $output;
    }
    /**
     * 获取邮件
     */
    static public function getUserEmail($id,$group_id){
            $count = Message::model()->getUserMessage($id,$group_id);
        return $count;
    }
    static public function getUserEvent($uid){
        $count = Event::model()->getCountEvent($uid);
        return $count;
    }



    /**
     * Ajax方式返回数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type AJAX返回数据格式
     * @return void
     */
    static public function ajaxReturn($data,$type='') {
        if(empty($type)) $type  =   'JSON';
        switch (strtoupper($type)){
            case 'JSON' :
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode($data));
            case 'XML'  :
                // 返回xml格式数据
                header('Content-Type:text/xml; charset=utf-8');
                exit(xml_encode($data));
            case 'JSONP':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                $handler  =   isset($_GET['callback']) ? $_GET['callback'] : 'jsonpReturn';
                exit($handler.'('.json_encode($data).');');
            case 'EVAL' :
                // 返回可执行的js脚本
                header('Content-Type:text/html; charset=utf-8');
                exit($data);
        }
    }

    static public function getAvatar($id,$size = 100){
        $dir1 = ceil($id / 10000);
        $dir2 = ceil($id % 10000 / 1000);
        $upload = Yii::app()->params['uploadPath'];
        $dir = Yii::app()->params['imgPath'].$upload.'avatar/'.$dir1.'/'.$dir2.'/'.$id.'/';
        if($size == 100){
            $url = $dir.'100x100.jpg';
            $curl = $upload.'avatar/'.$dir1.'/'.$dir2.'/'.$id.'/'.'100x100.jpg';
        }elseif($size == 200){
            $url = $dir.'200x200.jpg';
            $curl = $upload.'avatar/'.$dir1.'/'.$dir2.'/'.$id.'/'.'200x200.jpg';
        }elseif($size == 36){
            $url = $dir.'36x36.jpg';
            $curl = $upload.'avatar/'.$dir1.'/'.$dir2.'/'.$id.'/'.'36x36.jpg';
        }else{
            $url = Yii::app()->params['imgPath'].$upload.'avatar/'.$id.'/pictrue.jpg';
        }
        if(file_exists($curl)){
            return $url;
        }else{
            return Yii::app()->params['imgPath'].$upload.'public/avatar/12.jpg';
        }
    }
    /**
     * 显示时间
     */
    static public function showTime($t){
        $time = time() - $t;
        if($time < 60){
            $str = '刚刚发布';
        }else if($time < 60 * 60){
            $str = floor($time / 60).'分钟前发布';
        }else if($time < 60 * 60 * 24){
            if(date('Y-m-d')==date('Y-m-d',$t)){
                $str = '今天'.date('H:i',$t);
            }else{
                $str = '昨天'.date('H:i',$t);
            }
        }else if($time < 60 * 60 * 48){
            if(date('Y-m-d',strtotime("-1 day"))==date('Y-m-d',$t)){
                $str = '昨天'.date('H:i',$t);
            }else{
                $str = date('m月d日',$t);
            }
        }else if($time < 60 * 60 * 24* 365){
            $str = date('m月d日',$t);
        }else{
            $str = date('Y年m月d日',$t);
        }
        return $str;
    }

    /**
     * 字符截取
     *
     * @param $string
     * @param $length
     * @param $dot
     */
    public static function cutstr( $string, $length, $dot = '...', $charset = 'utf-8' ) {
        if ( strlen( $string ) <= $length )
            return $string;

        $pre = chr( 1 );
        $end = chr( 1 );
        $string = str_replace( array ( '&amp;' , '&quot;' , '&lt;' , '&gt;' ), array ( $pre . '&' . $end , $pre . '"' . $end , $pre . '<' . $end , $pre . '>' . $end ), $string );

        $strcut = '';
        if ( strtolower( $charset ) == 'utf-8' ) {

            $n = $tn = $noc = 0;
            while ( $n < strlen( $string ) ) {

                $t = ord( $string[$n] );
                if ( $t == 9 || $t == 10 || ( 32 <= $t && $t <= 126 ) ) {
                    $tn = 1;
                    $n ++;
                    $noc ++;
                } elseif ( 194 <= $t && $t <= 223 ) {
                    $tn = 2;
                    $n += 2;
                    $noc += 2;
                } elseif ( 224 <= $t && $t <= 239 ) {
                    $tn = 3;
                    $n += 3;
                    $noc += 2;
                } elseif ( 240 <= $t && $t <= 247 ) {
                    $tn = 4;
                    $n += 4;
                    $noc += 2;
                } elseif ( 248 <= $t && $t <= 251 ) {
                    $tn = 5;
                    $n += 5;
                    $noc += 2;
                } elseif ( $t == 252 || $t == 253 ) {
                    $tn = 6;
                    $n += 6;
                    $noc += 2;
                } else {
                    $n ++;
                }

                if ( $noc >= $length ) {
                    break;
                }

            }
            if ( $noc > $length ) {
                $n -= $tn;
            }

            $strcut = substr( $string, 0, $n );

        } else {
            for ( $i = 0; $i < $length; $i ++ ) {
                $strcut .= ord( $string[$i] ) > 127 ? $string[$i] . $string[++ $i] : $string[$i];
            }
        }

        $strcut = str_replace( array ( $pre . '&' . $end , $pre . '"' . $end , $pre . '<' . $end , $pre . '>' . $end ), array ( '&amp;' , '&quot;' , '&lt;' , '&gt;' ), $strcut );

        $pos = strrpos( $strcut, chr( 1 ) );
        if ( $pos !== false ) {
            $strcut = substr( $strcut, 0, $pos );
        }
        return $strcut . $dot;
    }

    /**
     * 描述格式化
     * @param  $subject
     */
    public static function clearCutstr ($subject, $length = 0, $dot = '...', $charset = 'utf-8')
    {
        if ($length) {
            return XUtils::cutstr(strip_tags(str_replace(array ("\r\n" ), '', $subject)), $length, $dot, $charset);
        } else {
            return strip_tags(str_replace(array ("\r\n" ), '', $subject));
        }
    }
    public static function returnError($array){
        foreach($array as $k=>$v){
            foreach($v as $value){
                $error[] = $value;
            }
        }
        return $error[0];
    }

}



/**
 * XML编码
 * @param mixed $data 数据
 * @param string $root 根节点名
 * @param string $item 数字索引的子节点名
 * @param string $attr 根节点属性
 * @param string $id   数字索引子节点key转换的属性名
 * @param string $encoding 数据编码
 * @return string
 */
function xml_encode($data, $root='think', $item='item', $attr='', $id='id', $encoding='utf-8') {
    if(is_array($attr)){
        $_attr = array();
        foreach ($attr as $key => $value) {
            $_attr[] = "{$key}=\"{$value}\"";
        }
        $attr = implode(' ', $_attr);
    }
    $attr   = trim($attr);
    $attr   = empty($attr) ? '' : " {$attr}";
    $xml    = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>";
    $xml   .= "<{$root}{$attr}>";
    $xml   .= data_to_xml($data, $item, $id);
    $xml   .= "</{$root}>";
    return $xml;
}

/**
 * 数据XML编码
 * @param mixed  $data 数据
 * @param string $item 数字索引时的节点名称
 * @param string $id   数字索引key转换为的属性名
 * @return string
 */
function data_to_xml($data, $item='item', $id='id') {
    $xml = $attr = '';
    foreach ($data as $key => $val) {
        if(is_numeric($key)){
            $id && $attr = " {$id}=\"{$key}\"";
            $key  = $item;
        }
        $xml    .=  "<{$key}{$attr}>";
        $xml    .=  (is_array($val) || is_object($val)) ? data_to_xml($val, $item, $id) : $val;
        $xml    .=  "</{$key}>";
    }
    return $xml;
}


